//
//  PersonView.m
//  SoundPill
//
//  Created by 宋旭东 on 15/10/19.
//  Copyright © 2015年 宋旭东. All rights reserved.
//

#import "PersonView.h"

#import "Musician.h"
#import "Work.h"
@interface PersonView ()<MJRefreshBaseViewDelegate,UITableViewDelegate, UITableViewDataSource>
{
    int page;
    int lastPage;
    int pages;
        NSString *_filePath;
    MJRefreshHeaderView *header;
    MJRefreshFooterView *fotter;
} 
@end

@implementation PersonView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadRelation:) name:@"reloadRelation" object:nil];
        self.musicianArray = [NSMutableArray array];
        [self createTabelView];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"person"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadPersonDataWithResponseObject:content pag:1];
            page = 1;
        } else {
            [header beginRefreshing];
        }

    }
    return self;
}
-(void)reloadRelation:(NSNotification *)notification
{
    NSDictionary *dict = notification.object;
    if (_musicianArray.count > 0) {
        Musician *rankModel = _musicianArray[_index];
        if ([[[dict valueForKey:@"data"] valueForKey:@"id"] isEqualToString:rankModel.userId]) {
            if ([[[dict valueForKey:@"meta"] valueForKey:@"following"] boolValue] == NO) {
                rankModel.relation = @"0";
                [_musicianArray replaceObjectAtIndex:_index withObject:rankModel];
                [_tableView reloadData];
            } else {
                if ([[[dict valueForKey:@"meta"] valueForKey:@"followed"] boolValue] == YES) {
                    rankModel.relation = @"2";
                    [_musicianArray replaceObjectAtIndex:_index withObject:rankModel];
                    [_tableView reloadData];
                } else {
                    rankModel.relation = @"1";
                    [_musicianArray replaceObjectAtIndex:_index withObject:rankModel];
                    [_tableView reloadData];
                }
            }
        }
    }
}
- (void)createTabelView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
//    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSeparatorColor:[UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000]];
    [self addSubview:self.tableView];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    header = [MJRefreshHeaderView header];
    header.scrollView = _tableView;
    header.delegate = self;
    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _tableView;
    fotter.delegate = self;
}
- (void)hideFooterView
{
    fotter.hidden = YES;
}
#pragma mark -- cell的线到头
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark -- cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ([UIScreen mainScreen].bounds.size.height -45 -64) / 8 + ([UIScreen mainScreen].bounds.size.width - 30 - 9) / 4 + 35;
}

#pragma mark -- cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _musicianArray.count;
}

#pragma mark -- 重用池
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"reuse";
    PersonTableViewCell *cell = (PersonTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
//        PersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[PersonTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_musicianArray.count > 0) {
        cell.musician = _musicianArray[indexPath.row];
//        cell.plazadataModel = _musicianArray[indexPath.row];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"personPop" object:nil];
}
#pragma mark - 数据请求
- (void)requestData:(int)pag Refreshing:(MJRefreshBaseView *)refreshView
{
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/discover?p=%d&type=%ld", pag,_type];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self reloadPersonDataWithResponseObject:responseObject pag:pag];
        [refreshView endRefreshing];
        if (pag == 1) {
            //            BOOL result =
//            [operation.responseData writeToFile:_filePath atomically:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [refreshView endRefreshing];
    }]; 
}
- (void)reloadPersonDataWithResponseObject:(id)responseObject pag:(int)pag
{
    NSMutableDictionary *musicianData = [responseObject objectForKey:@"data"];
    for (NSMutableDictionary *bigDic in musicianData) {
        Musician *musician = [[Musician alloc] init];
        musician.avatar = [bigDic objectForKey:@"avatar"];
        musician.userName = [bigDic objectForKey:@"username"];
        musician.relation = [bigDic objectForKey:@"follow"];
        musician.userId = [bigDic objectForKey:@"id"];
        if ([[bigDic objectForKey:@"introduce"] isKindOfClass:[NSNull class]]) {
            musician.introduce = @"";
        } else {
            musician.introduce = [bigDic objectForKey:@"introduce"];
        }
        NSMutableDictionary *worksDic = [bigDic objectForKey:@"works"];
        NSMutableArray *coverArr = [NSMutableArray array];
        NSMutableArray *nameArr = [NSMutableArray array];
        NSMutableArray *idArr = [NSMutableArray array];
        for (NSMutableDictionary *smallDic in worksDic) {
            Work *work = [[Work alloc] init];
            work.workCover = [smallDic objectForKey:@"cover"];
            work.workName = [smallDic objectForKey:@"title"];
            work.workid = [smallDic objectForKey:@"id"];
            [coverArr addObject:work.workCover];
            [nameArr addObject:work.workName];
            [idArr addObject:work.workid];
            musician.workCoverArr = coverArr;
            musician.workNameArr = nameArr;
            musician.workidArr = idArr;
        }
        [self.musicianArray addObject:musician];
    }
    NSDictionary *meta = [responseObject valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || page == pages) {
            [self hideFooterView];
        }
    }
    [_tableView reloadData];
}
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    //    NSLog(@"%@----开始进入刷新状态", refreshView.class);
    
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [fotter endRefreshing];
        [_musicianArray removeAllObjects];
        [self requestData:page Refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            [self hideFooterView];
        } else {
            page++;
            //            lastPage = page;
            [self requestData:page Refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    //    NSLog(@"%@----刷新完毕", refreshView.class);
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
